package com.token;

import com.token.annotation.TokenAnnotation;
import com.token.handler.TokenHandler;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;
@Slf4j
@Component
@Setter
public class TokenIntercepter implements HandlerInterceptor {

    private final static String ATTR="_Token";

    private TokenHandler tokenHandler;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            final HandlerMethod handlerMethod=(HandlerMethod)handler;
            final Class<?> beanType = handlerMethod.getBeanType();
            final Method method = handlerMethod.getMethod();
            TokenAnnotation annotation=null;
            if(beanType.isAnnotationPresent(TokenAnnotation.class)){
                annotation = beanType.getAnnotation(TokenAnnotation.class);
            }
            if(method.isAnnotationPresent(TokenAnnotation.class)){
                annotation=method.getAnnotation(TokenAnnotation.class);
            }
            if(null==annotation){
                return true;
            }
            log.info("Token Intercepter:{}",request);
            Map<String,String[]> paramMap = request.getParameterMap();
            String token = tokenHandler.generatorToken("yangjingjing");
            request.setAttribute(ATTR,token);
            log.info("Token generatorToken:{}",token);
            return tokenHandler.isExit(token, annotation.timeout());
        }
        return true;
    }
}
